package com.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.system.entity.SysRole;
import com.system.entity.SysRoleRel;
import com.system.entity.SysUser;
import com.system.exception.ServiceException;
import com.system.page.SysUserModel;
import com.system.service.SysRoleService;
import com.system.service.SysUserService;

import common.base.entity.BaseEntity.DELETED;
import common.base.entity.BaseEntity.STATE;
import common.base.util.MethodUtil;
import common.base.util.SessionUtils;
import common.base.util.StringUtil;
import common.base.web.BaseAction;

 
@Controller
@RequestMapping("/sysUser") 
public class SysUserAction extends BaseAction{
	
	private final static Logger log= Logger.getLogger(SysUserAction.class);
	
	// Servrice start
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private SysUserService<SysUser> sysUserService; 
	
	// Servrice start
	@Autowired(required=false) 
	private SysRoleService<SysRole> sysRoleService; 
	
		
	/**
	 * ilook 首页
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/list") 
	public ModelAndView list(SysUserModel model,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
//		List<SysUser> dataList = sysUserService.queryByList(model);
//		//设置页面数据
//		context.put("dataList", dataList);
		return forword("sys/sysUser",context); 
	}
	
	/**
	 * 用户信息管理：用户管理
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/list2") 
	public ModelAndView list2(SysUserModel model,HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
//		model.setCompany("company");
//		List<SysUser> dataList = sysUserService.queryByList(model);
//		//设置页面数据
//		context.put("dataList", dataList);
		return forword("company/sysUser",context); 
	}
	
	
	/**
	 * json 列表页面
	 * @param url
	 * @param classifyId
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/dataList") 
	public Map<String, Object> dataList(SysUserModel model) throws Exception{
		List<SysUser> dataList = sysUserService.queryByList(model);
		for(SysUser user: dataList){
			List<SysRole> list = sysRoleService.queryByUserid(user.getId());
			user.setRoleStr(rolesToStr(list));
		}
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		return jsonMap;
	}
	
	/**
	 * 角色列表转成字符串
	 * @param list
	 * @return
	 */
	private String rolesToStr(List<SysRole> list){
		if(list == null || list.isEmpty()){
			return null;
		}
		StringBuffer str = new StringBuffer();
		for(int i=0;i<list.size();i++){
			SysRole role = list.get(i);
			str.append(role.getRoleName());
			if((i+1) < list.size()){
				str.append(",");
			}
		}
		return str.toString();
	}
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String, Object> save(SysUser bean,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = new HashMap<String,Object>();
		int count = sysUserService.getUserCountByEmail(bean.getEmail());
		if(bean.getId() == null){
			if(count > 0){
				throw new ServiceException("用户已存在.");
			}
			bean.setDeleted(DELETED.NO.key);
			bean.setCompany("0");
			bean.setLoginCount(0);
			bean.setPwd(MethodUtil.MD5(bean.getPwd()));
			sysUserService.add(bean);
		}else{
			if(count > 1){
				throw new ServiceException("用户已存在.");
			}
			bean.setPwd(MethodUtil.MD5(bean.getPwd()));
			sysUserService.updateBySelective(bean);
		}
		return sendSuccessMessage("保存成功~");
	}
	
	
	
	@ResponseBody
	@RequestMapping("/getId")
	public Map<String, Object> getId(Integer id,HttpServletResponse response) throws Exception{
		Map<String,Object>  context = getRootMap();
		SysUser bean  = sysUserService.queryById(id);
		if(bean  == null){
			return sendFailureMessage("没有找到对应的记录!");
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		return context;
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(Integer[] id,HttpServletResponse response) throws Exception{
		sysUserService.delete(id);
		return sendSuccessMessage("删除成功");
	}
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/updatePwd")
	public Map<String, Object> updatePwd(Integer id,String oldPwd,String newPwd,HttpServletRequest request,HttpServletResponse response) throws Exception{
		boolean isAdmin = SessionUtils.isAdmin(request); //是否超级管理员
		SysUser bean  = sysUserService.queryById(id);
		if(bean.getId() == null || DELETED.YES.key == bean.getDeleted()){
			return sendFailureMessage("用户不存在");
		}
		if(StringUtils.isBlank(newPwd)){
			return sendFailureMessage("请输入新密码");
		}
		//不是超级管理员，匹配旧密码
		if(!isAdmin && !MethodUtil.ecompareMD5(oldPwd,bean.getPwd())){
			return sendFailureMessage("旧密码错误");
		}
		bean.setPwd(MethodUtil.MD5(newPwd));
		sysUserService.update(bean);
		return sendSuccessMessage("修改成功");
	}
	
	/**
	 * 系统用户授权页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userRole") 
	public ModelAndView  userRole(HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		return forword("/sys/sysUserRole", context);
	}
	
	/**
	 * 用户授权页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userRole2") 
	public ModelAndView  userRole2(HttpServletRequest request) throws Exception{
		Map<String,Object>  context = getRootMap();
		return forword("/company/sysUserRole", context);
	}
	
//	/**
//	 * 用户授权列表
//	 * @param model
//	 * @param response
//	 * @throws Exception
//	 */
//	@RequestMapping("/userList") 
//	public void userList(SysUserModel model,HttpServletResponse response) throws Exception{
//		model.setState(STATE.ENABLE.key);
//		dataList(model);
//	}

	
	/**
	 * 系统用户授权列表
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/userList") 
	public Map<String, Object> userList(SysUserModel model,HttpServletRequest request) throws Exception{
		model.setState(STATE.ENABLE.key);
		SysUser userLogin = SessionUtils.getUser(request);
		if(StringUtil.isNotEmpty(userLogin.getCompany()) && !"0".equals(userLogin.getCompany())){
			model.setCompany(userLogin.getCompany());
		}else if(StringUtil.isNotEmpty(userLogin.getCompany()) && "0".equals(userLogin.getCompany())){
			model.setCompany("admin");
		}
		List<SysUser> dataList = sysUserService.queryByList(model);
		for(SysUser user: dataList){
			List<SysRole> list = sysRoleService.queryByUserid(user.getId());
			user.setRoleStr(rolesToStr(list));
		}
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		return jsonMap;
	}
	
	/**
	 * 用户授权列表
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/userList2") 
	public Map<String, Object> userList2(SysUserModel model,HttpServletRequest request) throws Exception{
		model.setState(STATE.ENABLE.key);
		SysUser userLogin = SessionUtils.getUser(request);
		if(StringUtil.isNotEmpty(userLogin.getCompany()) && !"0".equals(userLogin.getCompany())){
			model.setCompany(userLogin.getCompany());
		}else if(StringUtil.isNotEmpty(userLogin.getCompany()) && "0".equals(userLogin.getCompany())){
			model.setCompany("admin");
		}
		List<SysUser> dataList = sysUserService.queryByList(model);
		for(SysUser user: dataList){
			List<SysRole> list = sysRoleService.queryByUserid(user.getId());
			user.setRoleStr(rolesToStr(list));
		}
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("total",model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		return jsonMap;
	}
	
	
	/**
	 * 查询用户信息
	 * @param id
	 * @param response
	 * @return 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getUser") 
	public Map<String, Object> getUser(Integer id,HttpServletResponse response)  throws Exception{
		Map<String,Object>  context = getRootMap();
		SysUser bean  = sysUserService.queryById(id);
		if(bean  == null){
			return sendFailureMessage("没有找到对应的记录!");
		}
		Integer[] roleIds = null;
		List<SysRoleRel>  roles  =sysUserService.getUserRole(bean.getId());
		if(roles != null){
			roleIds = new Integer[roles.size()];
			int i = 0;
			for(SysRoleRel rel : roles ){
				roleIds[i] = rel.getRoleId();
				i++;
			}
		}
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("id", bean.getId());
		data.put("email", bean.getEmail());
		data.put("roleIds", roleIds);
		context.put(SUCCESS, true);
		context.put("data", data);
		return context;
		
	}
	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return 
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/addUserRole")
	public Map<String, Object> addUserRole(Integer id,Integer roleIds[]) throws Exception{
		sysUserService.addUserRole(id, roleIds);
		return sendSuccessMessage("保存成功");
	}
}